<template>
    <div class="commodity-info-container">
        <div class="page-title-container">
            <el-icon class="title-icon">
                <Goods />
            </el-icon>
            <h1 class="page-title">商品信息管理</h1>
        </div>
        <!-- 商品信息管理卡片 -->
        <el-card>
            <!-- 工具栏按钮靠右显示 -->
            <div class="toolbar-right">
                <el-button class="btn-refresh" @click="resetAndFetch" type="primary" round>
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </el-button>
                <el-button class="btn-config" @click="showConfig = true" type="info" round>
                    <el-icon>
                        <Setting />
                    </el-icon>
                </el-button>
                <el-button class="btn-more" @click="toggleMoreQuery" type="warning" round>
                    <el-icon>
                        <Filter />
                    </el-icon>
                </el-button>
            </div>
            <!-- 搜索区域 -->
            <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 12px;">
                <!-- 全选/反选按钮 -->
                <el-button @click="toggleSelectAll" type="primary">全选/反选</el-button>
                <!-- 批量删除按钮 -->
                <el-button @click="openBatchDeleteDialog" type="danger" :disabled="multipleSelection.length === 0">批量删除</el-button>
                <!-- 添加商品按钮 -->
                <el-button type="success" @click="openAddDialog">添加商品</el-button>
            </div>

            <!-- 更多查询条件区域 -->
            <el-form v-if="showMoreQuery" :inline="true" style="margin-bottom: 12px;">
                <el-form-item label="商品名称">
                    <el-input v-model="dateinfo.FoodcommoditiesName" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="生产企业">
                    <el-input v-model="dateinfo.Manufacturer" placeholder="请输入生产企业" />
                </el-form-item>
                <el-form-item label="生产许可证号">
                    <el-input v-model="dateinfo.ProductionLicense" placeholder="请输入生产许可证号" />
                </el-form-item>
                <el-form-item label="保质期(天)">
                    <el-input-number v-model="dateinfo.ShelfLifeDays" :min="1" :max="99999" placeholder="请输入保质期" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">查询</el-button>
                    <el-button @click="resetMoreQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 商品信息表格 -->
            <el-table :data="tableData" style="width: 100%" v-loading="loading" border @selection-change="handleSelectionChange" ref="tableRef">
                <!-- 多选列 -->
                <el-table-column type="selection" width="55" />
                <!-- 表格列定义保持不变 -->
                <el-table-column type="index" label="ID" width="60" />
                <!-- 商品名称列 -->
                <el-table-column v-if="visibleColumns.includes('FoodcommoditiesName')" prop="FoodcommoditiesName"
                    label="商品名称" width="150" />
                <!-- 批次号列 -->
                <el-table-column v-if="visibleColumns.includes('BatchNumber')" prop="BatchNumber" label="批次号"
                    width="110" />
                <!-- 保质期列 -->
                <el-table-column v-if="visibleColumns.includes('ShelfLifeDays')" prop="ShelfLifeDays" label="保质期(天)"
                    width="90" />
                <!-- 生产许可证列 -->
                <el-table-column v-if="visibleColumns.includes('ProductionLicense')" prop="ProductionLicense"
                    label="生产许可证" width="150" />
                <!-- 生产企业列 -->
                <el-table-column v-if="visibleColumns.includes('Manufacturer')" prop="Manufacturer" label="生产企业"
                    width="180" />
                <!-- 完善度列 -->
                <el-table-column v-if="visibleColumns.includes('Perfect')" prop="Perfect" label="完善度" width="100" />
                <!-- 创建人列 -->
                <el-table-column v-if="visibleColumns.includes('Founder')" prop="Founder" label="创建人" width="100" />
                <!-- 创建时间列 -->
                <el-table-column v-if="visibleColumns.includes('CreateTime')" prop="CreateTime" label="创建时间"
                    width="170">
                    <template #default="sole">
                        {{ moment(sole.row.CreateTime).format("YYYY-MM-DD HH:mm:ss") }}
                    </template>
                </el-table-column>
                <!-- 修改人列 -->
                <el-table-column v-if="visibleColumns.includes('Modifier')" prop="Modifier" label="修改人" width="100" />
                <!-- 操作列 -->
                <el-table-column fixed="right" label="操作" min-width="250">
                    <template #default="sole">
                      
                            <el-button :icon="View" text type="primary" size="small"
                                @click="goToDetails(sole.row)">详情</el-button>
                            <el-button :icon="Edit" text type="warning" size="small"
                                @click="editRow(sole.row)">修改</el-button>
                            <el-button :icon="Delete" text type="danger" size="small"
                                @click="deleteRow(sole.row)">删除</el-button>
                            <el-button :icon="Download" text type="info" size="small" @click="openExportDialog(sole.row)">导出溯源码</el-button>
                   
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div style="margin-top: 16px; display: flex; justify-content: center;">
                <el-pagination v-model:current-page="dateinfo.PageIndex" v-model:page-size="dateinfo.PageSize"
                    :page-sizes="[10, 20, 30, 40, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <!-- 列配置弹窗 -->
            <el-dialog v-model="showConfig" title="列显示配置" width="400px">
                <el-checkbox-group v-model="visibleColumns">
                    <el-checkbox label="FoodcommoditiesName">商品名称</el-checkbox>
                    <el-checkbox label="BatchNumber">批次号</el-checkbox>
                    <el-checkbox label="ShelfLifeDays">保质期(天)</el-checkbox>
                    <el-checkbox label="ProductionLicense">生产许可证</el-checkbox>
                    <el-checkbox label="Manufacturer">生产企业</el-checkbox>
                    <el-checkbox label="Perfect">完善度</el-checkbox>
                    <el-checkbox label="Founder">创建人</el-checkbox>
                    <el-checkbox label="CreateTime">创建时间</el-checkbox>
                    <el-checkbox label="Modifier">修改人</el-checkbox>
                </el-checkbox-group>
                <template #footer>
                    <el-button @click="showConfig = false">关闭</el-button>
                </template>
            </el-dialog>
        </el-card>

        <!-- 添加商品弹窗 -->
        <el-dialog v-model="addDialogVisible" title="添加新商品" width="500px" @close="closeAddDialog">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px">
                <el-form-item label="商品名称" prop="FoodcommoditiesId">
                    <el-select v-model="addForm.FoodcommoditiesId" placeholder="请选择商品名称" style="width: 100%;">
                        <el-option v-for="item in shangpin" :key="item.FoodcommoditiesId"
                            :label="item.FoodcommoditiesName" :value="item.FoodcommoditiesId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次号" prop="BatchNumber">
                    <el-input v-model="addForm.BatchNumber" placeholder="请输入生产批次号" />
                </el-form-item>
                <el-form-item label="保质期(天)" prop="ShelfLifeDays">
                    <el-input-number v-model="addForm.ShelfLifeDays" :min="1" placeholder="请输入保质期天数"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="生产许可证号" prop="ProductionLicense">
                    <el-input v-model="addForm.ProductionLicense" placeholder="请输入生产许可证号" />
                </el-form-item>
                <el-form-item label="生产企业" prop="Manufacturer">
                    <el-input v-model="addForm.Manufacturer" placeholder="请输入生产企业" />
                </el-form-item>
                <el-form-item label="封面图" prop="CoverImageUrl">

                     <el-upload class="avatar-uploader"
                        :action="CommodityInfoWrite.defaults.baseURL + '/api/Picture/upload'"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.CoverImageUrl" :src="getFullImageUrl(addForm.CoverImageUrl)" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeAddDialog">取 消</el-button>
                    <el-button type="primary" @click="submitAddForm" :loading="submitLoading">提 交</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改商品弹窗 -->
        <el-dialog v-model="editDialogVisible" title="修改商品信息" width="500px">
            <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="120px">
                <el-form-item label="商品名称" prop="FoodcommoditiesId">
                    <el-select v-model="editForm.FoodcommoditiesId" placeholder="请选择商品名称" style="width: 100%;">
                        <el-option v-for="item in shangpin" :key="item.FoodcommoditiesId"
                            :label="item.FoodcommoditiesName" :value="item.FoodcommoditiesId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次号" prop="BatchNumber">
                    <el-input v-model="editForm.BatchNumber" placeholder="请输入生产批次号" />
                </el-form-item>
                <el-form-item label="保质期(天)" prop="ShelfLifeDays">
                    <el-input-number v-model="editForm.ShelfLifeDays" :min="1" placeholder="请输入保质期天数"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="生产许可证号" prop="ProductionLicense">
                    <el-input v-model="editForm.ProductionLicense" placeholder="请输入生产许可证号" />
                </el-form-item>
                <el-form-item label="生产企业" prop="Manufacturer">
                    <el-input v-model="editForm.Manufacturer" placeholder="请输入生产企业" />
                </el-form-item>
                <el-form-item label="封面图" prop="CoverImageUrl">

                    <el-upload class="avatar-uploader"
                        :action="CommodityInfoWrite.defaults.baseURL + '/api/Picture/upload'"
                        :show-file-list="false"
                        :on-success="handleEditAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="editForm.CoverImageUrl" :src="getFullImageUrl(editForm.CoverImageUrl)" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitEditForm" :loading="submitLoading">保 存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 批量删除确认弹窗 -->
        <el-dialog v-model="batchDeleteDialogVisible" title="确认删除" width="400px">
            <div style="margin: 24px 0; font-size: 16px;">
                确认删除已选的 {{ multipleSelection.length }} 个溯源商品？
            </div>
            <template #footer>
                <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleBatchDelete" :loading="batchDeleteLoading">确定</el-button>
            </template>
        </el-dialog>

        <!-- 导出溯源码弹窗 -->
        <el-dialog v-model="exportDialogVisible" title="导出设置" width="400px">
            <el-form :model="exportForm">
                <el-form-item label="导出数量">
                    <el-input-number v-model="exportForm.ExportCount" :min="1" :max="100" />
                </el-form-item>
                <el-form-item label="二维码尺寸">
                    <el-input-number v-model="exportForm.QrCodeSize" :min="100" :max="1000" />
                </el-form-item>
                <el-form-item label="格式">
                    <el-select v-model="exportForm.Format">
                        <el-option label="PNG" value="PNG" />
                        <el-option label="JPG" value="JPG" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleExport">导出</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
// 导入Vue相关功能
import { onMounted, reactive, ref, computed } from 'vue'
// 导入Element Plus组件
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
// 导入时间处理库
import moment from 'moment';
// 导入自定义的HTTP请求工具
import { CommodityInfoRead, CommodityInfoWrite } from '@/utils/axionrequest';
import { Plus, Refresh, Setting, Filter, View, Edit, Delete, Download, Goods } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useRouter } from 'vue-router'
import type { Ref } from 'vue'
import { QRCodeGenerator, type TraceabilityData } from '@/utils/qrCodeGenerator'

const Username = localStorage.getItem('Username')

//图片上传操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    addForm.CoverImageUrl = response.data.ImageUrl
}

const handleEditAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    editForm.CoverImageUrl = response.data.ImageUrl
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg'
        && rawFile.type !== 'image/gif' && rawFile.type !== 'image/bmp' && rawFile.type !== 'image/webp'
    ) {
        ElMessage.error('支持jpg, jpeg, png, gif, bmp, webp格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('文件大小限制5MB!')
        return false
    }
    return true
}

// 响应式数据定义
// 表格数据数组
const tableData = ref([])
// 总数据条数
const totalCount = ref(0)
// 加载状态标识
const loading = ref(false)

// 查询参数对象（响应式）
const dateinfo = reactive({
    PageIndex: 1,        // 当前页码
    PageSize: 10,         // 每页显示条数
    FoodcommoditiesName: '',  // 商品名称搜索关键词
    Manufacturer: '',
    ProductionLicense: '',
    ShelfLifeDays: null
})

// 添加商品相关数据
const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const submitLoading = ref(false)

// 编辑商品相关数据
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive({
    CommodityId: 0,
    FoodcommoditiesId: '',
    BatchNumber: '',
    ShelfLifeDays: null,
    ProductionLicense: '',
    Manufacturer: '',
    CoverImageUrl: '',
    Founder: '',
    Modifier: Username,
    Inspectionreport:''
})

// 添加表单数据
const addForm = reactive({
    FoodcommoditiesId: '',
    BatchNumber: '',
    ShelfLifeDays: null,
    ProductionLicense: '',
    Manufacturer: '',
    CoverImageUrl: '',
    Founder: Username,
    Modifier: ''
})

// 表单验证规则
const addFormRules: FormRules = {
    FoodcommoditiesId: [
        { required: true, message: '请选择商品名称', trigger: 'change' }
    ],
    BatchNumber: [
        { required: true, message: '请输入生产批次号', trigger: 'blur' },
        { max: 30, message: '生产批次号最多30位字符', trigger: 'blur' }
    ],
    ShelfLifeDays: [
        { required: true, message: '请输入保质期天数', trigger: 'blur' },
        { type: 'number', min: 1, max: 99999, message: '保质期天数必须在1-99999之间', trigger: 'blur' }
    ],
    ProductionLicense: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { max: 30, message: '生产许可证号最多30位字符', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]+$/, message: '生产许可证号只能包含数字和字母', trigger: 'blur' }
    ],
    Manufacturer: [
        { required: true, message: '请输入生产企业', trigger: 'blur' },
        { max: 30, message: '生产企业最多30位字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/, message: '生产企业只能包含中文、字母和数字', trigger: 'blur' }
    ],
    CoverImageUrl: [
        { required: true, message: '请输入封面图URL', trigger: 'blur' }
    ],
}

/**
 * 获取商品数据
 * 调用API获取商品列表信息
 */
const fetchData = () => {
    try {
        // 使用自定义HTTP工具发送GET请求
        CommodityInfoRead.get('/api/Commodity/SearchCommodities', { params: dateinfo }).then(res => {
            // 更新表格数据
            tableData.value = res.data.PageData
            // 更新总数据条数
            totalCount.value = res.data.TotalCount
        })
    } catch (e) {
        // 网络错误处理
        ElMessage.error('网络错误')
    } finally {
        loading.value = false
    }
}

//获取商品值（下拉框）
const shangpin = ref()

const shangdata = () => {
    CommodityInfoRead.get('/api/Commodity/SearchFoodcommodities').then(res => {
        shangpin.value = res.data.data
        console.log(shangpin);
    })
}

/**
 * 打开添加商品弹窗
 */
const openAddDialog = () => {
    addDialogVisible.value = true
    // 重置表单
    Object.assign(addForm, {
        FoodcommoditiesId: '',
        BatchNumber: '',
        ShelfLifeDays: null,
        ProductionLicense: '',
        Manufacturer: '',
        CoverImageUrl: '',
        Founder: Username,
        Modifier: ''
    })
}

/**
 * 关闭添加商品弹窗
 */
const closeAddDialog = () => {
    addDialogVisible.value = false
    addFormRef.value?.resetFields()
}

/**
 * 提交添加表单
 */
const submitAddForm = async () => {
    if (!addFormRef.value) return

    try {
        await addFormRef.value.validate()
        submitLoading.value = true

        console.log("addForm:", addForm);


        // 调用添加商品API
        const response = await CommodityInfoWrite.post('/api/Commodity/CreateCommodities', addForm)

        if (response.data.code === 200) {
            ElMessage.success('添加商品成功')
            addDialogVisible.value = false
            fetchData() // 刷新列表
            console.log(response);

        } else {
            ElMessage.error(response.data.msg || '添加商品失败')
        }

    } catch (error: any) {
        if (error.response) {
            ElMessage.error(error.response.data.message || '添加商品失败')
        } else {
            ElMessage.error('网络错误，请稍后重试')
        }
    } finally {
        submitLoading.value = false
    }
}

/**
 * 组件挂载时执行
 * 初始化加载商品数据
 */
onMounted(() => {
    fetchData()
    shangdata()
})

/**
 * 处理每页显示条数变化
 * @param val 新的每页显示条数
 */
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    // 更新每页显示条数
    dateinfo.PageSize = val
    // 重新获取数据
    fetchData()
}

/**
 * 处理当前页码变化
 * @param val 新的页码
 */
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    // 更新当前页码
    dateinfo.PageIndex = val
    // 重新获取数据
    fetchData()
}

const showMoreQuery = ref(false)
const showConfig = ref(false)
const visibleColumns = ref([
    'FoodcommoditiesName',
    'BatchNumber',
    'ShelfLifeDays',
    'ProductionLicense',
    'Manufacturer',
    'Perfect',
    'Founder',
    'CreateTime',
    'Modifier'
])
const toggleMoreQuery = () => {
    showMoreQuery.value = !showMoreQuery.value
}

const resetAndFetch = () => {
    dateinfo.FoodcommoditiesName = '';
    dateinfo.Manufacturer = '';
    dateinfo.PageIndex = 1;
    // 如果有更多查询条件，也一并清空
    fetchData();
}

const resetMoreQuery = () => {
    dateinfo.Manufacturer = '';
    dateinfo.ProductionLicense = '';
    dateinfo.ShelfLifeDays = null;
}

const router = useRouter()

// 详情跳转
const goToDetails = (row: any) => {
    router.push({ name: 'Detailsinfo', params: { id: row.CommodityId } })
    // 可选：详情页返回时刷新，可用事件或路由守卫
}

// 修改操作
const editRow = (row: any) => {
    // 数据回填到编辑表单
    Object.assign(editForm, row);
    editForm.Modifier = Username; // 设置修改人
    editDialogVisible.value = true;

     console.log('editForm:',editForm);
};

// 提交编辑表单
const submitEditForm = async () => {
    if (!editFormRef.value) return;

    await editFormRef.value.validate();

    submitLoading.value = true;
    try {
        const response = await CommodityInfoWrite.put('/api/Commodity/UpdateCommodity', editForm);
        if (response.data.code === 200) {
            ElMessage.success('更新成功');
            editDialogVisible.value = false;
            fetchData();
        } else {
            ElMessage.error(response.data.msg || '更新失败');
        }
    } catch (error: any) {
        ElMessage.error('网络错误或更新失败');
    } finally {
        submitLoading.value = false;
    }
}

// 删除操作
const deleteRow = (row: any) => {
    ElMessageBox.confirm(
        '确认删除该溯源商品?',
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {

                var data = {
                    CommodityId: row.CommodityId
                }
                const response = await CommodityInfoWrite.delete('/api/Commodity/DeleteCommodityInfo', { data });

                if (response.data.code === 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    });
                    fetchData(); // 刷新当前页面
                } else {
                    ElMessage({
                        type: 'error',
                        message: response.data.message || '操作失败，请稍后再试',
                    });
                }
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '删除失败，请稍后再试',
                });
            }
        })
        .catch(() => {
            // 用户点击了取消
            ElMessage({
                type: 'info',
                message: '已取消删除',
            });
        });
};

const tableRef = ref()
const multipleSelection: Ref<any[]> = ref([])

const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}

const toggleSelectAll = () => {
    const table = tableRef.value
    if (!table) return
    if (multipleSelection.value.length === tableData.value.length) {
        // 已全选，执行反选（清空）
        table.clearSelection()
    } else {
        // 未全选，执行全选
        tableData.value.forEach(row => {
            table.toggleRowSelection(row, true)
        })
    }
}

const batchDeleteDialogVisible = ref(false)
const batchDeleteLoading = ref(false)

const openBatchDeleteDialog = () => {
    batchDeleteDialogVisible.value = true
}

const handleBatchDelete = async () => {
    if (multipleSelection.value.length === 0) return
    batchDeleteLoading.value = true
    try {
        const ids = multipleSelection.value.map(item => item.CommodityId)
        const response = await CommodityInfoWrite.delete('/api/Commodity/BatchDeleteCommodity', { data: { CommodityId: ids } })
        if (response.data.code === 200) {
            ElMessage.success(`已删除${ids.length}个溯源商品`)
            batchDeleteDialogVisible.value = false
            multipleSelection.value = []
            fetchData()
        } else {
            ElMessage.error('删除失败，请稍后再试')
        }
    } catch (e) {
        ElMessage.error('删除失败，请稍后再试')
    } finally {
        batchDeleteLoading.value = false
    }
}

const exportDialogVisible = ref(false)
const exportForm = reactive({
    CommodityId: null,
    QrCodeSize: 300,
    Format: 'PNG',
    ExportCount: 1
})
let currentRow: any = null

const openExportDialog = (row: any) => {
    exportDialogVisible.value = true
    exportForm.CommodityId = row.CommodityId
    exportForm.ExportCount = 1
    currentRow = row
}

const handleExport = async () => {
    try {
        if (!currentRow) {
            ElMessage.error('未选择商品')
            return
        }

        // 构建溯源数据
        const traceabilityData: TraceabilityData = {
            commodityId: currentRow.CommodityId,
            commodityName: currentRow.FoodcommoditiesName || '',
            batchNumber: currentRow.BatchNumber || '',
            manufacturer: currentRow.Manufacturer || '',
            productionLicense: currentRow.ProductionLicense || '',
            shelfLifeDays: currentRow.ShelfLifeDays || 0,
            createTime: currentRow.CreateTime || '',
            traceabilityUrl: ''
        }

        // 生成二维码内容为详情页URL
        const qrContent = QRCodeGenerator.buildTraceabilityUrl(traceabilityData)
        const qrCodeDataUrl = await QRCodeGenerator.generateTraceabilityQRCode(traceabilityData, {
            size: exportForm.QrCodeSize,
            margin: 2,
            color: { dark: '#000000', light: '#FFFFFF' }
        })

        // 下载二维码
        const fileName = `溯源码_${currentRow.CommodityId}_${currentRow.FoodcommoditiesName || '商品'}.png`
        QRCodeGenerator.downloadQRCode(qrCodeDataUrl, fileName)

        ElMessage.success('导出成功')
        exportDialogVisible.value = false
    } catch (e) {
        console.error('导出失败:', e)
        ElMessage.error('导出失败')
    }
}

function getFullImageUrl(url: string) {
  if (!url) return ''
  // 如果是http开头但host不是baseURL，强制替换为baseURL
  if (url.startsWith('http') && !url.startsWith(CommodityInfoWrite.defaults.baseURL)) {
    const idx = url.indexOf('/Img/')
    if (idx !== -1) {
      url = url.substring(idx)
    }
    return CommodityInfoWrite.defaults.baseURL + url
  }
  return url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url
}

</script>


<style scoped>
.commodity-info-container {
    padding: 20px;
    background-color: #f4f6f9;
    /* 不设置height和overflow，继承父级滚动 */
}

.page-title-container {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 20px;
    background: linear-gradient(135deg, #5b86e5 0%, #36d1dc 100%);
    color: white;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.title-icon {
    font-size: 32px;
}

.page-title {
    font-size: 26px;
    font-weight: 600;
    margin: 0;
}

.toolbar-right {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.action-buttons {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: flex-start;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.enterprise-info-container {
    margin: 24px 0;
}
.el-card {
    padding: 16px;
}
.info-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}
.info-label {
    color: #666;
    margin-right: 8px;
    min-width: 80px;
    font-weight: bold;
}
</style>